<template>
  <div class="vue-admin-beautiful-wrapper" :class="classObj">
    <div
      v-if="'horizontal' === layout"
      class="layout-container-horizontal"
      :class="{
        fixed: header === 'fixed',
        'no-tabs-bar': tabsBar === 'false' || tabsBar === false,
      }"
    >
      <div :class="header === 'fixed' ? 'fixed-header' : ''">
        <vab-top-bar />
        <div
          v-if="tabsBar === 'true' || tabsBar === true"
          :class="{ 'tag-view-show': tabsBar }"
        >
          <div class="vab-main">
            <vab-tabs-bar />
          </div>
        </div>
      </div>
      <div class="vab-main main-padding">
        <vab-ad />
        <vab-app-main />
      </div>
    </div>
    <div
      v-else
      class="layout-container-vertical"
      :class="{
        fixed: header === 'fixed',
        'no-tabs-bar': tabsBar === 'false' || tabsBar === false,
      }"
    >
      <div
        v-if="device === 'mobile' && collapse === false"
        class="mask"
        @click="handleFoldSideBar"
      />
      <vab-side-bar />
      <div class="vab-main" :class="collapse ? 'is-collapse-main' : ''">
        <div :class="header === 'fixed' ? 'fixed-header' : ''">
          <vab-nav-bar />
          <vab-tabs-bar v-if="tabsBar === 'true' || tabsBar === true" />
        </div>
        <vab-ad />
        <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="24">
          <el-card shadow="never">
            <div slot="header">
              <span>设备总负载率</span>
            </div>
            <div style="text-align: center">
              <el-progress
                type="circle"
                :percentage="deviceLoadRate"
                :color="deviceLoadColor"
              ></el-progress>
            </div>
            <br />
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="24">
          <el-card shadow="never">
            <div slot="header">
              <span>人员总负载率</span>
            </div>
            <div style="text-align: center">
              <el-progress
                type="circle"
                :percentage="peopleLoadRate"
                :color="peopleLoadColor"
              ></el-progress>
            </div>
            <br />
          </el-card>
        </el-col>
        <div class="table-container" style="width: 95%; margin: 0 auto">
          <vab-query-form>
            <vab-query-form-left-panel>
              <el-button
                icon="el-icon-plus"
                type="primary"
                disabled
                @click="handleAdd"
              >
                添加
              </el-button>
              <h2 style="margin-left: 10px">
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="暂不支持添加资源"
                  placement="right"
                >
                  <i class="el-icon-info"></i>
                </el-tooltip>
              </h2>
            </vab-query-form-left-panel>
          </vab-query-form>

          <el-table
            ref="tableSort"
            v-loading="listLoading"
            :data="resourceList"
            :element-loading-text="elementLoadingText"
            :height="height"
            :row-style="{ height: '100px' }"
            :cell-style="{ textAlign: 'center' }"
            :header-cell-style="{ textAlign: 'center' }"
            @selection-change="setSelectRows"
            @sort-change="tableSortChange"
          >
            <el-table-column
              show-overflow-tooltip
              prop="resourceId"
              label="资源ID"
            ></el-table-column>
            <el-table-column
              show-overflow-tooltip
              label="资源数量"
              prop="resourceNum"
            ></el-table-column>
            <el-table-column show-overflow-tooltip label="资源种类">
              <template #default="{ row }">
                <el-tooltip
                  :content="row.resourceType"
                  class="item"
                  effect="dark"
                  placement="top-start"
                >
                  <el-tag :type="row.resourceType | statusFilter">
                    {{ row.resourceType }}
                  </el-tag>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column label="资源负载率" width="500px">
              <template #default="{ row }">
                <div :id="row.resourceId" style="height: 200px"></div>
              </template>
            </el-table-column>
            <!--            <el-table-column show-overflow-tooltip label="操作" width="180px">-->
            <!--              <template #default="{ row }">-->
            <!--                <el-button type="primary" disabled @click="handleEdit(row)">-->
            <!--                  编辑-->
            <!--                </el-button>-->
            <!--                <el-button type="danger" disabled @click="handleDelete(row)">-->
            <!--                  删除-->
            <!--                </el-button>-->
            <!--              </template>-->
            <!--            </el-table-column>-->
          </el-table>
        </div>
        <vab-app-main />
      </div>
    </div>
    <el-backtop />
  </div>
</template>

<script>
  import { mapActions, mapGetters } from 'vuex'
  import { tokenName } from '@/config'
  import * as echarts from 'echarts'
  import {
    getDeviceLoadRatio,
    getStaffLoadRatio,
    getLoadRatio,
  } from '@/api/resource/getLoadRatio'
  import { getAllResources } from '../../api/resource/getAllResources'
  import { getCookie } from '@/utils/cookie'

  export default {
    name: 'ResourceManagement',
    filters: {
      statusFilter(type) {
        const statusMap = {
          班组: 'gray',
          线体: 'danger',
        }
        return statusMap[type]
      },
    },
    data() {
      return {
        imgShow: true,
        resourceList: [
          {
            resourceId: '12345',
            resourceNum: '11',
            resourceType: '班组',
            loadRatio: [1, 2, 3, 4, 5, 6, 7],
            loadRatioColor: [
              '#c23531',
              '#2f4554',
              '#61a0a8',
              '#d48265',
              '#91c7ae',
              '#749f83',
              '#ca8622',
            ],
          },
        ],
        imageList: [],
        listLoading: true,
        layout: 'total, sizes, prev, pager, next, jumper',
        total: 0,
        background: true,
        selectRows: '',
        elementLoadingText: '正在加载...',
        queryForm: {
          pageNo: 1,
          pageSize: 20,
          title: '',
        },
        curDate: '2020-12-21', // 当前日期
        //负载率
        deviceLoadRate: 0, // 当前设备总负载率
        deviceLoadColor: '#000000', // 当前设备负载率颜色
        peopleLoadRate: 0, // 当前人员总负载率
        peopleLoadColor: '#000000', //当前人员总负载率颜色
      }
    },
    computed: {
      ...mapGetters({
        layout: 'settings/layout',
        tabsBar: 'settings/tabsBar',
        collapse: 'settings/collapse',
        header: 'settings/header',
        device: 'settings/device',
      }),
      classObj() {
        return {
          mobile: this.device === 'mobile',
        }
      },
      height() {
        return this.$baseTableHeight()
      },
    },
    created() {
      this.fetchData()
      // this.getDeviceLoadRate()
      // this.getStaffLoadRate()
    },
    beforeMount() {
      window.addEventListener('resize', this.handleResize)
    },
    beforeDestroy() {
      window.removeEventListener('resize', this.handleResize)
    },
    mounted() {
      this.oldLayout = this.layout
      const userAgent = navigator.userAgent
      if (userAgent.includes('Juejin')) {
        this.$baseAlert(
          'vue-admin-beautiful不支持在掘金内置浏览器演示，请手动复制以下地址到浏览器中查看http://mpfhrd48.sanxing.uz7.cn/vue-admin-beautiful'
        )
      }
      const isMobile = this.handleIsMobile()
      if (isMobile) {
        if (isMobile) {
          //横向布局时如果是手机端访问那么改成纵向版
          this.$store.dispatch('settings/changeLayout', 'vertical')
        } else {
          this.$store.dispatch('settings/changeLayout', this.oldLayout)
        }
        this.$store.dispatch('settings/toggleDevice', 'mobile')
        setTimeout(() => {
          this.$store.dispatch('settings/foldSideBar')
        }, 2000)
      } else {
        this.$store.dispatch('settings/openSideBar')
      }
      this.$nextTick(() => {
        window.addEventListener(
          'storage',
          (e) => {
            if (e.key === tokenName || e.key === null) window.location.reload()
            if (e.key === tokenName && e.value === null)
              window.location.reload()
          },
          false
        )
        this.fetchData()
      })
    },
    methods: {
      ...mapActions({
        handleFoldSideBar: 'settings/foldSideBar',
      }),
      handleIsMobile() {
        return document.body.getBoundingClientRect().width - 1 < 992
      },
      handleResize() {
        if (!document.hidden) {
          const isMobile = this.handleIsMobile()
          if (isMobile) {
            //横向布局时如果是手机端访问那么改成纵向版
            this.$store.dispatch('settings/changeLayout', 'vertical')
          } else {
            this.$store.dispatch('settings/changeLayout', this.oldLayout)
          }

          this.$store.dispatch(
            'settings/toggleDevice',
            isMobile ? 'mobile' : 'desktop'
          )
        }
      },
      tableSortChange() {
        const imageList = []
        this.$refs.tableSort.tableData.forEach((item, index) => {
          imageList.push(item.img)
        })
        this.imageList = imageList
      },
      setSelectRows(val) {
        this.selectRows = val
      },
      handleAdd() {
        this.$refs['edit'].showEdit()
      },
      handleEdit(row) {
        this.$refs['edit'].showEdit(row)
      },
      handleDelete(row) {
        if (row.id) {
          this.$baseConfirm('你确定要删除当前项吗', null, async () => {
            const { msg } = await doDelete({ ids: row.id })
            this.$baseMessage(msg, 'success')
            this.fetchData()
          })
        } else {
          if (this.selectRows.length > 0) {
            const ids = this.selectRows.map((item) => item.id).join()
            this.$baseConfirm('你确定要删除选中项吗', null, async () => {
              const { msg } = await doDelete({ ids: ids })
              this.$baseMessage(msg, 'success')
              this.fetchData()
            })
          } else {
            this.$baseMessage('未选中任何行', 'error')
            return false
          }
        }
      },
      handleSizeChange(val) {
        this.queryForm.pageSize = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.queryForm.pageNo = val
        this.fetchData()
      },
      handleQuery() {
        this.queryForm.pageNo = 1
        this.fetchData()
      },
      async fetchData() {
        this.listLoading = true
        this.curDate = getCookie('cur_date')
        this.getLoadRate()
        this.resourceList = this.getResourceList()
        setTimeout(() => {
          this.listLoading = false
        }, 500)
      },
      drawEcharts() {
        console.log(this.resourceList)
        for (let i = 0; i < this.resourceList.length; i++) {
          let resource = this.resourceList[i]
          let myChart = echarts.init(
            document.getElementById(resource.resourceId)
          )
          let option = {
            xAxis: {
              type: 'category',
            },
            yAxis: {
              type: 'value',
              show: false,
            },
            tooltip: {
              show: false,
              showContent: false,
            },
            series: [
              {
                data: resource.loadRatio,
                type: 'bar',
                label: {
                  show: true,
                  formatter: '{c}%',
                },
                itemStyle: {
                  barBorderRadius: [10, 10, 0, 0],
                  normal: {
                    color: function (params) {
                      var colorList = resource.loadRatioColor
                      return colorList[params.dataIndex]
                    },
                  },
                },
              },
            ],
          }
          console.log(option)
          myChart.setOption(option)
          myChart.resize()
        }
      },
      getDeviceLoadRate() {
        getDeviceLoadRatio(this.curDate).then((res) => {
          this.deviceLoadRate = parseFloat(res)
          this.calculateDeviceLoadColor()
        })
      },

      calculateDeviceLoadColor() {
        if (parseFloat(this.deviceLoadRate) < 20) {
          this.deviceLoadColor = '#98FB98'
        } else if (parseFloat(this.deviceLoadRate) < 40) {
          this.deviceLoadColor = '#B0E0E6'
        } else if (parseFloat(this.deviceLoadRate) < 60) {
          this.deviceLoadColor = '#FFEC8B'
        } else if (parseFloat(this.deviceLoadRate) < 80) {
          this.deviceLoadColor = '#F4A460'
        } else {
          this.deviceLoadColor = '#CD5555'
        }
      },

      getStaffLoadRate() {
        getStaffLoadRatio(this.curDate).then((res) => {
          this.peopleLoadRate = parseFloat(res)
          this.calculatePeopleLoadColor()
        })
      },

      calculatePeopleLoadColor() {
        if (parseFloat(this.peopleLoadRate) < 20) {
          this.peopleLoadColor = '#98FB98'
        } else if (parseFloat(this.peopleLoadRate) < 40) {
          this.peopleLoadColor = '#B0E0E6'
        } else if (parseFloat(this.peopleLoadRate) < 60) {
          this.peopleLoadColor = '#FFEC8B'
        } else if (parseFloat(this.peopleLoadRate) < 80) {
          this.peopleLoadColor = '#F4A460'
        } else {
          this.peopleLoadColor = '#CD5555'
        }
      },

      getLoadRate() {
        getLoadRatio(this.curDate).then((res) => {
          this.peopleLoadRate = parseFloat(res.staffLoadRatio)
          this.deviceLoadRate = parseFloat(res.deviceLoadRatio)
          this.calculateDeviceLoadColor()
          this.calculatePeopleLoadColor()
        })
      },

      getResourceList() {
        getAllResources(this.curDate).then((res) => {
          this.resourceList = []
          for (let i = 0; i < res.length; i++) {
            let item = res[i]
            this.resourceList.push(item)
            if (this.resourceList[i].resourceType === 1) {
              this.resourceList[i].resourceType = '线体'
            } else {
              this.resourceList[i].resourceType = '班组'
            }
            this.resourceList[i].loadRatioColor = []
            for (let j = 0; j < this.resourceList[i].loadRatio.length; j++) {
              if (this.resourceList[i].loadRatio[j] < 20) {
                this.resourceList[i].loadRatioColor.push('#98FB98')
              } else if (this.resourceList[i].loadRatio[j] < 40) {
                this.resourceList[i].loadRatioColor.push('#B0E0E6')
              } else if (this.resourceList[i].loadRatio[j] < 60) {
                this.resourceList[i].loadRatioColor.push('#FFEC8B')
              } else if (this.resourceList[i].loadRatio[j] < 80) {
                this.resourceList[i].loadRatioColor.push('#F4A460')
              } else {
                this.resourceList[i].loadRatioColor.push('#CD5555')
              }
            }
          }
          this.total = this.resourceList.length
          this.drawEcharts()
        })
      },
    },
  }
</script>

<style lang="scss" scoped>
  @mixin fix-header {
    position: fixed;
    top: 0;
    right: 0;
    left: 0;
    z-index: $base-z-index - 2;
    width: 100%;
    overflow: hidden;
  }

  .vue-admin-beautiful-wrapper {
    position: relative;
    width: 100%;
    height: 100%;

    .layout-container-horizontal {
      position: relative;

      &.fixed {
        padding-top: calc(#{$base-top-bar-height} + #{$base-tabs-bar-height});
      }

      &.fixed.no-tabs-bar {
        padding-top: $base-top-bar-height;
      }

      ::v-deep {
        .vab-main {
          width: 88%;
          margin: auto;
        }

        .fixed-header {
          @include fix-header;
        }

        .tag-view-show {
          background: $base-color-white;
          box-shadow: $base-box-shadow;
        }

        .nav-bar-container {
          .fold-unfold {
            display: none;
          }
        }

        .main-padding {
          .app-main-container {
            margin-top: $base-padding;
            margin-bottom: $base-padding;
            background: $base-color-white;
          }
        }
      }
    }

    .layout-container-vertical {
      position: relative;

      .mask {
        position: fixed;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        z-index: $base-z-index - 1;
        width: 100%;
        height: 100vh;
        overflow: hidden;
        background: #000;
        opacity: 0.5;
      }

      &.fixed {
        padding-top: calc(#{$base-nav-bar-height} + #{$base-tabs-bar-height});
      }

      &.fixed.no-tabs-bar {
        padding-top: $base-nav-bar-height;
      }

      .vab-main {
        position: relative;
        min-height: 100%;
        margin-left: $base-left-menu-width;
        background: #f6f8f9;
        transition: $base-transition;

        ::v-deep {
          .fixed-header {
            @include fix-header;

            left: $base-left-menu-width;
            width: $base-right-content-width;
            box-shadow: $base-box-shadow;
            transition: $base-transition;
          }

          .nav-bar-container {
            position: relative;
            box-sizing: border-box;
          }

          .tabs-bar-container {
            box-sizing: border-box;
          }

          .app-main-container {
            width: calc(100% - #{$base-padding} - #{$base-padding});
            margin: $base-padding auto;
            background: $base-color-white;
            border-radius: $base-border-radius;
          }
        }

        &.is-collapse-main {
          margin-left: $base-left-menu-width-min;

          ::v-deep {
            .fixed-header {
              left: $base-left-menu-width-min;
              width: calc(100% - 65px);
            }
          }
        }
      }
    }

    &-frame {
      display: flex;
      flex-flow: column nowrap;
      justify-content: space-between;

      .price-bar {
        color: red !important;
      }
      .tiger-trend-charts {
        height: 60px;
        min-width: 100px;
      }
    }

    /* 手机端开始 */
    &.mobile {
      ::v-deep {
        .el-pager,
        .el-pagination__jump {
          display: none;
        }

        .layout-container-vertical {
          .el-scrollbar.side-bar-container.is-collapse {
            width: 0;
          }

          .vab-main {
            width: 100%;
            margin-left: 0;
          }
        }

        .vab-main {
          .fixed-header {
            left: 0 !important;
            width: 100% !important;
          }
        }
      }
    }

    /* 手机端结束 */
  }
</style>
